  <template>
	<view class="zai-box">
        <scroll-view scroll-y class="page">
            <view class="text-center" :style="[{animation: 'show ' + 0.4+ 's 1'}]">
				<image src="https://ylb123.oss-cn-hangzhou.aliyuncs.com/app/logo-1024.png" mode='aspectFit' class="zai-logo "></image>
				<view class="zai-title text-shadow ">
					医疗帮
					<text class="second-title">/用户登录</text>
				</view>
			</view>
            <view class="box padding-lr-xl login-paddingtop" :style="[{animation: 'show ' + 0.6+ 's 1'}]">
				
				<view class="cu-form-group margin-top  shadow-warp" :class="[shape=='round'?'round':'']">
					<view class="title"><text class="cuIcon-mobile margin-right-xs"></text>手机号:</view>
					<input placeholder="请输入手机号" type="number" maxlength="11" v-model="phoneNo"></input>
				</view>
				<view class="cu-form-group margin-top shadow-warp" :class="[shape=='round'?'round':'']">
					<view class="title"><text class="cuIcon-lock margin-right-xs"></text>验证码:</view>
					<input class="uni-input" placeholder="请输入验证码" maxlength="6" v-model="smsCode"/>
					<view class="action">
						<button class="cu-btn line-blue sm" :disabled="!isSendSMSEnable" @click="onSMSSend"> {{ getSendBtnText }}</button>
					</view>
				</view>
				
				<view class="service-agreement-con">
					<view @tap="serviceAgreeChange()">
						<text class="iconfont margin-right-sm"
							:class="serviceAgree?'cyIcon-checkbox-checked':'cyIcon-checkbox'"></text> 
							同意服务协议
					</view>
					<view class="agree-title" @tap="toServiceAgreement()">
						《医疗帮用户注册与隐私保护服务协议》
					</view>
				</view>
				
				<view class="padding text-center margin-top">
					<button class="cu-btn bg-cyan lg margin-right shadow" :loading="loading" :class="[shape=='round'?'round':'']"
						@tap="onSMSLogin"><text space="emsp">{{loading ? "登录中...":"安全登录"}}</text>
					</button>
					<button class="cu-btn line-orange lg margin-left shadow" :loading="loading" :class="[shape=='round'?'round':'']"
						@tap="targetRegister">会员注册
					</button>
					<!-- <view style="margin-top: 100upx;"
						@tap="toStartPage()">
						启动页
					</view> -->
				</view>
                
				<!-- #ifdef APP-PLUS -->
				<view class="padding flex flex-direction  text-center">
					版本{{version}}
				</view>
				<!-- #endif -->
				
            </view>
        </scroll-view>
		<!-- 登录加载弹窗 -->
		<view class="cu-load load-modal" v-if="loading">
			<!-- <view class="cuIcon-emojifill text-orange"></view> -->
			<!-- <image src="https://static.jeecg.com/upload/test/login4_1595818039175.png" mode="aspectFit" class="round"></image> -->
			<image src="/static/logo/logo-1024.png" mode="aspectFit" class="round"></image>
			<view class="gray-text">登录中...</view>
		</view>
    </view>

</template>

<script>
	import {
		APP_VERSION,
		APP_MUST_PERMISSION_STATUS,
		
		USER_HAS_LOGIN,
		USER_ACCOUNT,
		USER_IDENTITY,
		USER_TOKEN,
		
		CUS_IS_VIP,
		CUS_VIP_LEVEL_ID,
		CUS_VIP_LEVEL_TITLE,
		CUS_VIP_START_TIME,
		CUS_VIP_END_TIME,
		COMMON_HTTP_ERROR_TIP,
	} from "@/common/util/constants"
	import { mapActions } from "vuex"
    import configService from '@/common/service/config.service.js';
	
    export default {
        data() {
            return {
				shape:'',//round 圆形
				loading: false,
				userName: 'admin',
				password: '123456',
				phoneNo: '',
				smsCode: '',
				showPassword: false, //是否显示明文
				loginWay: 1, //1: 账密，2：验证码
				smsCountDown: 0,
				smsCountInterval: null,
				toggleDelay: false,
				version:'',
				//第三方登录相关信息
				thirdType:"",
				thirdLoginInfo:"",
				thirdLoginState:false,
				bindingPhoneModal:false,
				thirdUserUuid:'',
				url: {
					bindingThirdPhone: '/sys/thirdLogin/bindingThirdPhone'
				},
				serviceAgree: false,	//协议条款(true-同意, false-不同意)
            };
        },
		onLoad:function(){			
			// #ifdef APP-PLUS
			/* let _userFirstTimeRun = plus.storage.getItem('userFirstTimeRun')
			console.log('login onLoad _userFirstTimeRun = ', _userFirstTimeRun)
			if(!_userFirstTimeRun){
				uni.redirectTo({
					url: '/pages/start-page/start-page'
				})
				return false
			} */
			
			let that=this
			plus.runtime.getProperty( plus.runtime.appid, function ( wgtinfo ) {
				that.version = wgtinfo.version
			});
			
			// #endif
		},
		computed: {
		      isSendSMSEnable() {
		        return this.smsCountDown <= 0 && this.phoneNo.length==11;
		      },
		      getSendBtnText() {
		        if (this.smsCountDown > 0) {
		          return this.smsCountDown + '秒后发送';
		        } else {
		          return '发送验证码';
		        }
		      },
		      canSMSLogin() {
		        return this.userName.length > 4 && this.smsCode.length > 4;
		      },
		      canPwdLogin() {
		        return this.userName.length > 4 && this.password.length > 4;
		      },
		},
        methods: {
			 ...mapActions([ "mLogin","PhoneLogin","ThirdLogin" ]),
			onLogin: function (){
			        if(!this.userName || this.userName.length==0){
			          this.$tip.toast('请填写用户名');
			          return;
			        }
			        if(!this.password || this.password.length==0){
			           this.$tip.toast('请填写密码');
			          return;
			        }
			        let loginParams = {
			          username:this.userName,
			          password:this.password
			        }
					this.loading=true;
			        this.mLogin(loginParams).then((res) => {
					  this.loading=false;
			          if(res.data.success){
						 // #ifdef APP-PLUS
						  this.saveClientId()
						 // #endif
						 // #ifndef APP-PLUS
						  this.$tip.success('登录成功!')
						  this.$Router.replaceAll({name:'index'})
						 // #endif
						}else{
			              this.$tip.alert(res.data.message);
			            }
			        }).catch((err) => {
			          let msg = err.data.message || "请求出现错误，请稍后再试"
			          this.loading=false;
					  this.$tip.alert(msg);
			        }).finally(()=>{
					  this.loading=false;
				})
			},
			//服务协议-查看
			toServiceAgreement(){
				uni.navigateTo({
					url: '/pages/singles/service-agreement'
				})
			},
			//服务协议-勾选操作
			serviceAgreeChange(){
				this.serviceAgree = !this.serviceAgree
			},
			//去启动页
			toStartPage(){
				uni.navigateTo({
					url: '../start-page/start-page'
				})
			},
			saveClientId(){
				var info = plus.push.getClientInfo();
				var cid = info.clientid;
				this.$http.get("/sys/user/saveClientId",{params:{clientId:cid}}).then(res=>{
					this.$tip.success('登录成功!')
					this.$Router.replaceAll({name:'index'})
				})
			},
			changePassword() {
				this.showPassword = !this.showPassword;
			},
			//发送短信
			onSMSSend() {
				let smsParams = {};
				smsParams.mobile=this.phoneNo;
				smsParams.smsmode="0";
				let checkPhone = new RegExp(/^[1]([3-9])[0-9]{9}$/);
                if(!smsParams.mobile || smsParams.mobile.length==0){
					this.$tip.toast('请输入手机号');
					return false
				}
				if(!checkPhone.test(smsParams.mobile)){
					this.$tip.toast('请输入正确的手机号');
					return false
				}
				this.smsCountDown = 60;
				this.startSMSTimer();
				this.$http.post("/sys/sms",smsParams).then(res=>{
				  if(res.data.success){
				  
				  }else{
					this.smsCountDown = 0;
					this.$tip.toast(res.data.message);
				  }
				});
			  },
			startSMSTimer() {
				this.smsCountInterval = setInterval(() => {
				  this.smsCountDown--;
				  if (this.smsCountDown <= 0) {
					clearInterval(this.smsCountInterval);
				  }
				}, 1000);
			},
			targetRegister(){
				uni.redirectTo({
				    url: '/pages/register/register'
				});
			},
			//短信登录 xxx
			onSMSLogin() {
				let that = this
				if(!that.phoneNo || that.phoneNo.length==0){
				  that.$tip.toast('请填写手机号');
				  return;
				}
				let checkPhone = new RegExp(/^[1]([3-9])[0-9]{9}$/);
				if(!checkPhone.test(that.phoneNo)){
					that.$tip.toast('手机号格式错误');
					return false
				}
				if(!that.smsCode || that.smsCode.length!=6){
				  that.$tip.toast('请填写正确短信验证码');
				  return;
				}
				if(!that.serviceAgree){
				  that.$tip.cyToast('请查阅服务协议并同意', '', 1500);
				  return false;
				}
				let _params = {
				  mobile:that.phoneNo,
				  captcha:that.smsCode
				};
				let app_must_permission_status = uni.getStorageSync('APP_MUST_PERMISSION_STATUS')
				uni.clearStorageSync();
				uni.setStorageSync('APP_MUST_PERMISSION_STATUS', app_must_permission_status)
				uni.showLoading({
					title: '登录中..',
					mask: true,
				})
				that.$http.post("/sys/phoneLogin",_params).then(res=>{
					if(res.data.success){
						uni.hideLoading()
						let _rv = res.data.result
						if(!_rv){
							that.$tip.toast('登录失败');
							return false;
						}
						if(_rv.userInfo.userIdentity==undefined || _rv.userInfo.userIdentity==null || _rv.userInfo.userIdentity==null){
						  that.$tip.toast('账户异常, 请联系客服处理');
						  return false;
						}
						if(!_rv.token || _rv.token.length<=1){
						  that.$tip.toast('账户认证失败, 请联系客服处理');
						  return false;
						}
						that.$tip.success('登录成功')
						uni.setStorageSync(APP_VERSION, that.version)
						uni.setStorageSync(APP_MUST_PERMISSION_STATUS, '1')
						uni.setStorageSync(USER_HAS_LOGIN, '1');
						uni.setStorageSync(USER_ACCOUNT, _rv.userInfo.phone);
						uni.setStorageSync(USER_IDENTITY, _rv.userInfo.userIdentity);
						uni.setStorageSync(USER_TOKEN, _rv.token);
						
						uni.setStorageSync(CUS_IS_VIP, _rv.is_vip?_rv.is_vip:'N');
						uni.setStorageSync(CUS_VIP_LEVEL_ID, _rv.vip_level_id?_rv.vip_level_id:'');
						uni.setStorageSync(CUS_VIP_LEVEL_TITLE, _rv.vip_level_title?_rv.vip_level_title:'');
						uni.setStorageSync(CUS_VIP_START_TIME, _rv.startTime?_rv.startTime:'');
						uni.setStorageSync(CUS_VIP_END_TIME, _rv.endtime?_rv.endtime:'');
						
						setTimeout(function() {
							that.$Router.replace({name:'index'})
						}, 600);
					}else{
						uni.hideLoading()
						that.$tip.cyToast(res.data.message);
					}
				}).catch(e => {
					uni.hideLoading()
					//that.$tip.cyToast(COMMON_HTTP_ERROR_TIP);
				});
			},
			loginSuccess() {
			  // 登陆成功，重定向到主页
			  this.$Router.replace({name:'index'})
			},
			requestFailed(err) {
			  this.$message.warning("登录失败")
			},
        },
		beforeDestroy() {
		    if (this.smsCountInterval) {
		        clearInterval(this.smsCountInterval);
		    }
		},
    }
</script>

<style>
	/* 服务协议 S */
	.service-agreement-con{
		margin-top: 40upx;
		color: #666666;
	}
	.service-agreement-con .iconfont{
		color: #E96141;
		font-size: 40upx;
	}
	
	.service-agreement-con .agree-title{
		padding-left: 50upx;
		margin-top: 20upx;
		color: #1CBBB4;
	}
	/* 服务协议 E */
	
    .login-paddingtop {
        padding-top: 100upx;
    }

    .zai-box {
        padding: 0 20upx;
        padding-top: 100upx;
        position: relative;
    }

    .zai-logo {
        width: 200upx;
        height: 150px;
    }

    .zai-title {
       font-size: 58upx;
       color: #000000;
       text-align: center;
    }
	.zai-title .second-title {
       font-size: 40upx;
	   color: #EA6040;
	}

    .input-placeholder, .zai-input {
        color: #94afce;
    }

    .zai-label {
        padding: 60upx 0;
        text-align: center;
        font-size: 30upx;
        color: #a7b6d0;
    }

    .zai-btn {
        background: #ff65a3;
        color: #fff;
        border: 0;
        border-radius: 100upx;
        font-size: 36upx;
    }

    .zai-btn:after {
        border: 0;
    }

    /*按钮点击效果*/
    .zai-btn.button-hover {
        transform: translate(1upx, 1upx);
    }

</style>
